<?php header( 'Content-type: text/html; charset=utf-8' );
// Awesome Facebook Application
//
// Name: orktest
// 
// v4
// working on accordion javascript
// fixed : FB is not defined (all browsers except ie failed). 
// solution : moving include for http://connect.facebook.net/en_US/all.js
// outside of FB async calling. Setting this include as separate tag.
// todo: 
// 1) scripts for supporting dropdown lists for sections
// 2) fix null in birthday field
// 3) try to use another method instead FB.Data.query for fetching friends info
// 4) user friendly 
// 5) upload to google svn
// 6) register app
// 7) outside configure.php, style.css and javascripts

require_once 'facebook-php-sdk/src/facebook.php';
require_once ('utils/KLogger.php');

$log = new KLogger ( "log/fbapp_log.txt" , KLogger::DEBUG );

// Create our Application instance.
$facebook = new Facebook(array(
  'appId' => '127996350606219',
  'secret' => 'df23d57022f4f004adfc0a495309f806',
  'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();

$me = null;
$uid = null;
// Session based API call.
if ($session) {
  try {
	
    $uid = $facebook->getUser();
	$log->LogInfo("_User [" . $uid . ", " . $_SERVER['REMOTE_ADDR'] . "]");
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

// login or logout url will be needed depending on current user state.
if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}

// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');

?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title>php-sdk</title>
    <style>
      body {
        font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
      }
      h1 a {
        text-decoration: none;
        color: #3b5998;
      }
      h1 a:hover {
        text-decoration: underline;
      }
	.accordionItem h2 { margin: 0; font-size: 1.1em; padding: 0.4em; color: #fff; background-color: #944; border-bottom: 1px solid #66d; }
	.accordionItem h2:hover { cursor: pointer; }
	.accordionItem div { margin: 0; padding: 1em 0.4em; background-color: #eef; border-bottom: 1px solid #66d; }
	.accordionItem.hide h2 { color: #000; background-color: #88f; }
	.accordionItem.hide div { display: none; }	  
    </style>
	
	
	    <script> 
    var accordionItems = new Array();
 
    function init() {
 
      // Grab the accordion items from the page
      var divs = document.getElementsByTagName( 'div' );
      for ( var i = 0; i < divs.length; i++ ) {
        if ( divs[i].className == 'accordionItem' ) accordionItems.push( divs[i] );
      }
 
      // Assign onclick events to the accordion item headings
      for ( var i = 0; i < accordionItems.length; i++ ) {
        var h2 = getFirstChildWithTagName( accordionItems[i], 'H2' );
        h2.onclick = toggleItem;
      }
 
      // Hide all accordion item bodies except the first
      for ( var i = 1; i < accordionItems.length; i++ ) {
        accordionItems[i].className = 'accordionItem hide';
      }
    }
 
    function toggleItem() {
      var itemClass = this.parentNode.className;
 
      // Hide all items
      for ( var i = 0; i < accordionItems.length; i++ ) {
        accordionItems[i].className = 'accordionItem hide';
      }
 
      // Show this item if it was previously hidden
      if ( itemClass == 'accordionItem hide' ) {
        this.parentNode.className = 'accordionItem';
      }
    }
 
    function getFirstChildWithTagName( element, tagName ) {
      for ( var i = 0; i < element.childNodes.length; i++ ) {
        if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
      }
    }
    </script>
	
	
  </head>
  <body  onload="init()">
    <!--
      We use the JS SDK to provide a richer user experience. For more info,
      look here: http://github.com/facebook/connect-js
    -->
    <div id="fb-root"></div>
	      <script src="http://connect.facebook.net/en_US/all.js">
      </script>

    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '<?php echo $facebook->getAppId(); ?>',
          session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location.reload();
        });
      };

      (function() {
        var e = document.createElement('script');
        //e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>
	
    <!--h1><a href="example.php">php-sdk</a></h1-->

    <?php if ($me): ?>
    <a href="<?php echo $logoutUrl; ?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
    </a>
    <?php else: ?>
    <div>
      Using JavaScript &amp; XFBML: <fb:login-button perms="email,user_birthday,friends_birthday,user_status,user_checkins"></fb:login-button>
    </div>
    <div>
      Without using JavaScript &amp; XFBML:
      <a href="<?php echo $loginUrl; ?>">
        <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
      </a>
    </div>
    <?php endif ?>

	<div class="accordionItem">
		<h2>Session</h2>
		<div>
		    <?php if ($me): ?>
		    <pre><?php print_r($session); ?></pre>
		</div>
	</div>
	
	<div class="accordionItem">
	    <h2>You</h2>
		<div>
		    <img src="https://graph.facebook.com/<?php echo $uid; ?>/picture">
		    <?php echo $me['name']; ?>
		</div>
	</div>

	<div class="accordionItem">
	    <h2>Your User Object</h2>
		<div>
			<pre><?php print_r($me); ?></pre>
		</div>
	</div>
	
    <?php else: 
		$log->LogInfo("_Guest [" . $_SERVER['REMOTE_ADDR'] . "]");
	?>
    <strong><em>You are not Connected.</em></strong>
    <?php endif ?>

	<div class="accordionItem">
	    <h2>Naitik</h2>
		<div>
		    <img src="https://graph.facebook.com/naitik/picture">
		    <?php echo $naitik['name']; ?>
		</div>
	</div>
	
	<div class="accordionItem">	
		<h2>Friends</h2>	
		<div id="test3"><p>Error while loading a friends list</p></div>
	</div>
	<!--?php echo "<div id=\"test3\"><p>aaaa</p></div>"; ?-->
	<script>
		var query3 = FB.Data.query('select birthday, uid, name from user where uid in' +
		' (select 	uid2 from friend where uid1={0})',<?php echo $uid; ?>); 
		FB.Data.waitOn([query3], function() {
			var html = '';
			var bd = '(disabled by user)';
			FB.Array.forEach(query3.value, function(row) {
				if(row.birthday)
				{ bd = row.birthday; }
				html += '<img src="https://graph.facebook.com/'
				+ row.uid + '/picture" title="' + row.name + '"/>'
				+ row.name + ", " + bd + '<br>';
			});
			document.getElementById('test3').innerHTML = html;
		});	 
	</script>

  </body>
</html>
